package org.wannatrak.android.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.entity.Credential;
import org.wannatrak.android.exceptions.HttpException;
import org.wannatrak.android.executions.ProjectService;
import org.wannatrak.android.formatter.TimeFormatter;
import org.wannatrak.android.helper.DateHelper;
import org.wannatrak.android.helper.DialogHelper;
import org.wannatrak.android.helper.UIHelper;
import org.wannatrak.android.intf.ClickAction;
import org.wannatrak.android.intf.DialogAction;
import org.wannatrak.android.service.WannatrakGPSService;

import java.util.Date;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-11-29 08:41:22 +0000 (Tue, 29 Nov 2011) $ 4:56 PM
 * @version: $Revision: 33 $
 * @id: $Id: SettingActivity.java 33 2011-11-29 08:41:22Z maxtulupov@gmail.com $
 */
public class SettingActivity extends AbstractContextMenuActivity {

    /**
     * thread for executing async login
     */
    private Thread t;

    /**
     * dialog that shows async execution
     */
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        String s = ApplicationContext.getSettingService().loadSetting("isTracking");
        boolean isTracking = Boolean.parseBoolean(s);
        if (isTracking) {
            restartService();
//            dialog = DialogHelper.createProgressDialog(SettingActivity.this);
//            final DialogHandler handler = new DialogHandler(dialog, SettingActivity.this);
//            dialog.show();
//            Runnable r = new Runnable() {
//                public void run() {
//                    Looper.prepare();
//                    try {
//                        ApplicationContext.getWannatrakService().continueTrack();
//                        restartService();
//                    } catch (HttpException e) {
//                        handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
//                    } finally {
//                        dialog.dismiss();
//                    }
//                }
//            };
//            t = new Thread(r);
//            t.start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        return super.onRetainNonConfigurationInstance();
    }

    private void init() {
        UIHelper.setActionToView(findViewById(R.id.openMapButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                Intent intent = new Intent(SettingActivity.this, ViewTrackActivity.class);
                startActivity(intent);
                return true;
            }
        });

        UIHelper.setActionToView(findViewById(R.id.changeUserButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                getContentResolver().delete(Credential.CONTENT_URI, null, null);
                ApplicationContext.getTrackHistoryService().clearHistory();
                startActivity(new Intent(SettingActivity.this, StartPageActivity.class));
                finish();
                return true;
            }
        });

        UIHelper.setActionToView(findViewById(R.id.deleteTrackButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                startActivity(new Intent(SettingActivity.this, DeleteTrackActivity.class));
                return true;
            }
        });

        String s = ApplicationContext.getSettingService().loadSetting("isTracking");
        boolean isTracking = Boolean.parseBoolean(s);
        if (isTracking) {
            initContinueTrack();
        } else {
            initStartTrack();
        }
    }

    private void initStartTrack() {
        findViewById(R.id.currentTrackLayout).setVisibility(View.GONE);
        findViewById(R.id.newTrackLayout).setVisibility(View.VISIBLE);
        initStartTrackFields();
    }

    private void initContinueTrack() {
        findViewById(R.id.trackName).setEnabled(false);
        findViewById(R.id.newTrackLayout).setVisibility(View.GONE);
        findViewById(R.id.currentTrackLayout).setVisibility(View.VISIBLE);
        initCurrentTrackFields();

    }

    /**
     * init fields for start new track
     */
    private void initStartTrackFields() {
        UIHelper.setActionToView(findViewById(R.id.startTrackButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                if (!UIHelper.isGpsEnabled(getApplicationContext())) {
                    DialogHelper.showNoGpsDialog(SettingActivity.this);
                    return true;
                }

                startActivity(new Intent(SettingActivity.this, StartTrackActivity.class));
                return true;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == DialogHelper.FROM_LOCATION_SETTINGS) {
            if (!UIHelper.isGpsEnabled(getApplicationContext())) {
                DialogHelper.showNoGpsDialog(SettingActivity.this);
            } else {
                startActivity(new Intent(SettingActivity.this, StartTrackActivity.class));
            }
        }
    }

    /**
     * init fields for view current track
     */
    private void initCurrentTrackFields() {
        ((TextView) findViewById(R.id.trackName)).setText(ApplicationContext.getSettingService().loadSetting("trackName"));
        ((TextView) findViewById(R.id.trackInterval)).setText(ApplicationContext.getSettingService().loadSetting("trackInterval"));
        ((TextView) findViewById(R.id.saveInterval)).setText(ApplicationContext.getSettingService().loadSetting("saveInterval"));
        DialogHelper.setTimeDialogToTextView(this, (TextView) findViewById(R.id.trackInterval), new DialogHelper.OnTimeSetListener() {

            public void onSet(TimePicker timePicker, int hours, int minutes) {
                Date date = DateHelper.getDate(1, 1, 1, hours, minutes);
                String format = ApplicationContext.getFormatter(TimeFormatter.class).format(date);
                if (updateTrack()) {
                    ApplicationContext.getSettingService().saveSetting("trackInterval", format);
                    restartService();
                }
            }
        });

        DialogHelper.setTimeDialogToTextView(this, (TextView) findViewById(R.id.saveInterval), new DialogHelper.OnTimeSetListener() {

            public void onSet(TimePicker timePicker, int hours, int minutes) {
                Date date = DateHelper.getDate(1, 1, 1, hours, minutes);
                String format = ApplicationContext.getFormatter(TimeFormatter.class).format(date);
                if (updateTrack()) {
                    ApplicationContext.getSettingService().saveSetting("saveInterval", format);
                    restartService();
                }
            }
        });

        UIHelper.setActionToView(findViewById(R.id.showOnMapButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                String name = ((TextView) findViewById(R.id.trackName)).getText().toString();
                Intent intent = new Intent(SettingActivity.this, ViewTrackActivity.class).putExtra("currentTrack", name);
                startActivity(intent);
                return true;
            }
        });

        UIHelper.setActionToView(findViewById(R.id.stopTrackButton), new ClickAction() {

            public boolean actionPerformed(View view) {
                dialog = DialogHelper.createProgressDialog(SettingActivity.this);
                final SuccessStopDialogHandler handler = new SuccessStopDialogHandler(dialog, SettingActivity.this);
                dialog.show();
                Runnable r = new Runnable() {
                    public void run() {
                        Looper.prepare();
                        try {
                            ApplicationContext.getWannatrakService().sendTracks();
                            try {
                                ApplicationContext.getWannatrakService().logout();
                            } finally {
                                ApplicationContext.getWannatrakService().login();
                            }
                            stopService();
                            ApplicationContext.getSettingService().saveSetting("isTracking", "false");
                            handler.sendMessage(handler.obtainMessage(1234));
                        } catch (HttpException e) {
                            handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
                        } finally {
                            dialog.dismiss();
                        }
                    }
                };
                t = new Thread(r);
                t.start();
                return true;
            }
        });

    }

    private boolean updateTrack() {
        dialog = DialogHelper.createProgressDialog(SettingActivity.this);
        final DialogHandler handler = new DialogHandler(dialog, SettingActivity.this);
        dialog.show();
        Runnable r = new Runnable() {
            public void run() {
                Looper.prepare();
                String name = ((TextView) findViewById(R.id.trackName)).getText().toString();
                String trackInterval = ((TextView) findViewById(R.id.trackInterval)).getText().toString();
                String saveInterval = ((TextView) findViewById(R.id.saveInterval)).getText().toString();
                try {
//                    ApplicationContext.getWannatrakService().continueTrack();
                    ApplicationContext.getWannatrakService().updateTrack(name, trackInterval, saveInterval);
                } catch (HttpException e) {
                    handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
                } finally {
                    dialog.dismiss();
                }
            }
        };
        t = new Thread(r);
        t.start();
        return true;
    }

    /**
     * stop and start service for sending coordinates with new Interval
     */
    private void restartService() {
        WannatrakGPSService service = ApplicationContext.getWannatrakGPSService();
        service.stopTracking();
        if (service.startTracking()) {
            Log.e(getClass().getSimpleName(), " try to start service");
            stopService(new Intent(this, ProjectService.class));
            startService(new Intent(this, ProjectService.class));
        }
    }

    private void stopService() {
        WannatrakGPSService service = ApplicationContext.getWannatrakGPSService();
        service.stopTracking();
        stopService(new Intent(this, ProjectService.class));
    }

    private class SuccessStopDialogHandler extends Handler {

        private Dialog dialog;

        private Context context;

        public SuccessStopDialogHandler(Dialog dialog, Context context) {
            this.dialog = dialog;
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what < 0) {
                UIHelper.createAlertDialog(context, (String) msg.obj, -1, true, (DialogAction[]) null).show();
            } else {
                init();
            }
        }
    }
}
